package com.lerning.edu.manage.controller;

import com.lerning.edu.beans.SysOpenid;
import com.lerning.edu.beans.SysUser;
import com.lerning.edu.commons.PwdUtils;
import com.lerning.edu.manage.common.GlobalVariableNames;
import com.lerning.edu.manage.common.security.shiro.session.SessionDAO;
import com.lerning.edu.manage.context.GlobalContext;
import com.lerning.edu.manage.security.FormAuthenticationFilter;
import com.lerning.edu.manage.security.SystemAuthorizingRealm.Principal;
import com.lerning.edu.manage.util.UserUtils;
import com.lerning.edu.services.SysOpenidService;
import com.lerning.edu.services.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * AuthController
 * 用户登录
 * @author FCHEN
 * @date 2015/11/11
 */
@Controller
public class WeCharAuthController extends BaseController {
    @Autowired
    private SessionDAO sessionDAO;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOpenidService sysOpenidService;
    /**
     * 登录
     *
//     * @param account
//     * @param pwd
     * @param request
     * @return
     */
    @RequestMapping(value = "/wechatLogin/login", method = RequestMethod.POST)
    public String login(HttpServletRequest request, Model model,
                        @RequestParam(value = "username", required = false)String username,
                        @RequestParam(value = "password", required = false)String password,
                        @RequestParam(value = "openid", required = false)String openid) {

        SysUser sysUser = sysUserService.queryUserByAccount(username);
        if(sysUser != null){
            String pwd = encrypt(password, sysUser.getSalt());
            if(pwd.equals(sysUser.getPwd())){
                SysOpenid sysOpenid = sysOpenidService.queryByOpenid(openid);
                if(sysOpenid == null){
                    SysOpenid sopid = new SysOpenid();
                    sopid.setAccount(sysUser.getAccount());
                    sopid.setName(sysUser.getName());
                    sopid.setUserId(sysUser.getId());
                    sopid.setOpenid(openid);

                    sysOpenidService.add(sopid);
                }
                return "weCharIndex";
            }else {
                return loginFail(request, model, openid);
            }
        }else {
            return loginFail(request, model, openid);
        }
    }

    /**
     * 登录失败，真正登录的POST请求由Filter完成
     */
    private String loginFail(HttpServletRequest request, Model model, String openid) {
        Principal principal = UserUtils.getPrincipal();
        // 如果已经登录，则跳转到管理首页
        if(principal != null){
            return "redirect:" + GlobalContext.getProperties(GlobalVariableNames.BASEPATH) + "/index";
        }
        String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
        boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
        String exception = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        String message = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);

        if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")){
            message = "用户或密码错误, 请重试.";
        }

        model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
        model.addAttribute(FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
        model.addAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
        model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);

        if (logger.isDebugEnabled()){
            logger.debug("login fail, active session size: {}, message: {}, exception: {}",
                    sessionDAO.getActiveSessions(false).size(), message, exception);
        }
        request.setAttribute("openid", openid);
        return "auth/login2";
    }

    private String encrypt(String pwd,String salt) {
        String sha384Hex = PwdUtils.saltPwd(pwd, salt);//这里可以选择自己的密码验证方式 比如 md5或者sha256等
        return sha384Hex;
    }
}
